import PostMate from "postmate"

export function closeIframe(code, iframes, iframeDom) {
  // 删除标签
  for (const [index, item] of iframes.entries()) {
    if (item.code === code) {
      // item.show = false
      iframes.splice(index, 1)
      break
    }
  }

  // 销毁通讯对象
  for (const [index, i] of iframeDom.entries()) {
    if (code === i.code) {
      i.obj.then(child => child.destroy())
      iframeDom.splice(index, 1)
      break
    }
  }
}
// 添加iframe标签
export function addIframe(data, vueObject) {
  vueObject.iframes.push(data)
  const params = data.params
  vueObject.$nextTick(() => {
    const iframeUrl = window.location.origin + '/#/' + data.url
    const allIframes = document.querySelectorAll('#iframe')
    const orderDom = allIframes[allIframes.length - 1]
    const handshake = new PostMate({
      container: orderDom,
      url: iframeUrl,
      name: data.code,
      classListArray: ["ik-iframe-content"]
    })
    vueObject.iframeDom.push({ code: data.code, obj: handshake })

    handshake.then(child => {
      // 链接函数
      child.on('someEvent', (data) => {
        child.frame.contentWindow.postMessage({
          params: params
        }, iframeUrl)
      })
      // 增加新的iframe标签
      // child.on('addIframe', (data) => {
      //   $this.addIframe(data)
      // })
    })
  })
}
// 回到指定iframe,其上层的iframe关掉
export function goIframe(code, iframes, iframeDom) {
  for (const [index, item] of iframes.entries()) {
    if (code === item.code) {
      iframes.splice(index + 1)
    }
  }
  let shengyuiframedom
  let selectIframe
  for (const [index, i] of iframeDom.entries()) {
    if (code === i.code) {
      shengyuiframedom = index
      selectIframe = i
      // i.obj.then(child => child.destroy())
      // iframeDom.splice(index, 1)
      break
    }
  }
  for (let index = shengyuiframedom + 1; index < iframeDom.length; index++) {
    iframeDom[index].obj.then(child => child.destroy())
  }
  iframeDom.splice(shengyuiframedom + 1)
  selectIframe.obj.then(child => {
    // child.child.refresh()
    child.call('refresh')
  })
}

export function creatIframe(docker, params, iframeDom, vueObject) {
  const handshake = new PostMate({
    container: docker,
    url: params.iframeUrl,
    name: params.code,
    classListArray: ["ik-iframe-content"]

  })
  iframeDom.push({ code: params.code, obj: handshake })
  handshake.then(child => {
    // 链接函数
    child.on('someEvent', (data) => {
      child.frame.contentWindow.postMessage({
        params: params.params
      }, params.iframeUrl)
    })
    // 增加新的iframe标签
    child.on('addIframe', (data) => {
      addIframe(data, vueObject)
    })
    // 回到指定iframe，上层都关闭
    child.on('goIframe', (data) => {
      goIframe(data, vueObject)
    })
    child.on('getIframeParams', (data) => {
      // vueObject.childIframeParams = data
      vueObject.getIframeParams(data)
    })
    child.on('closeIframe', (code) => {
      closeIframe(code, vueObject.iframes, vueObject.iframeDom)
    })
  })
}

